package com.ciwong.epaper.ui;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.res.TypedArray;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.TextView;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.bean.RfTokenInfo;
import com.ciwong.epaper.modules.me.dao.MeDao;
import com.ciwong.epaper.modules.me.ui.AgreementActivity;
import com.ciwong.epaper.modules.me.util.MeJumpManager;
import com.ciwong.epaper.modules.pad.contentprovider.LoginToken;
import com.ciwong.epaper.modules.pad.contentprovider.MyGradeWidgetProvider;
import com.ciwong.epaper.modules.pad.homeworkwidget.widget.HomeworkWidgetProvider;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.EJumpManager;
import com.ciwong.epaper.util.FeedbackUtil;
import com.ciwong.epaper.util.HttpRequest;
import com.ciwong.epaper.util.LoginUtil;
import com.ciwong.libs.utils.CWSys;
import com.ciwong.libs.utils.volley.BaseRequest;
import com.ciwong.mobilelib.application.BaseApplication;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.utils.BaseConstants;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * 启动页面
 * Created by lqi on 2017/2/22.
 */
public class SplashActivityDef extends Activity {
    private static final String TAG = "SplashActivity";
    private BaseRequest.VerifyInfo verifyInfo;
    private LoginToken mLoginToken;
    //是否来源于重新登录
    private boolean isReLogin;

    private TextView log_title;

    private String mLoginFrom;
    //是否是第一次登录
    private boolean isFirstUse = true;
    //是否同意隐私协议
    boolean privacyAgreement = false;
    private String packageName = "";

    private Handler handler = new Handler(Looper.getMainLooper());


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //如果是8.0系统的手机，并且认为是透明主题的Activity
        if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O && isTranslucentOrFloating()) {
            boolean result = fixOrientation();
            Log.e(TAG, "onCreate: " + "onCreate fixOrientation when Oreo, result = " + result);
        }
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_splash_layout);
        getIsFirstUse();
        initCreate();
    }


    @Override
    public void onResume() {
        super.onResume();
    }

    /**
     * 初始化加载
     */
    private void initCreate() {
        if (!this.isTaskRoot()) {
            Intent intent = getIntent();
            if (intent != null) {
                String action = intent.getAction();
                if (intent.hasCategory(Intent.CATEGORY_LAUNCHER) && Intent.ACTION_MAIN.equals(action)) {
                    finish();
                    return;
                }
            }
        }
        log_title = findViewById(R.id.log_title);
        if (EApplication.BRAND_ID == 570678343) {
            log_title.setVisibility(View.GONE);
        } else {
            log_title.setVisibility(View.VISIBLE);
        }

        Intent intent = getIntent();
        if (intent != null) {
            isReLogin = intent.getBooleanExtra(LoginToken.ACTION_KEY_RELOGIN, false);
            mLoginFrom = intent.getStringExtra(LoginToken.LOGIN_FROM);
        }

        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (EApplication.PLATFORM_ENV == EApplication.PLATFORM_PAD) {
                    queryTokenFromPad();
                } else {
                    checkToken();
                }
            }
        }, 100);

    }

    @Override
    public void setRequestedOrientation(int requestedOrientation) {
        if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O && isTranslucentOrFloating()) {
            Log.e(TAG, "setRequestedOrientation: " + "avoid calling setRequestedOrientation when Oreo.");
            return;
        }
        super.setRequestedOrientation(requestedOrientation);
    }

    private boolean isTranslucentOrFloating() {
        boolean isTranslucentOrFloating = false;
        try {
            int[] styleableRes = (int[]) Class.forName("com.android.internal.R$styleable").getField("Window").get(null);
            final TypedArray ta = obtainStyledAttributes(styleableRes);
            Method m = ActivityInfo.class.getMethod("isTranslucentOrFloating", TypedArray.class);
            m.setAccessible(true);
            isTranslucentOrFloating = (boolean) m.invoke(null, ta);
            m.setAccessible(false);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isTranslucentOrFloating;
    }

    private boolean fixOrientation() {
        try {
            Field field = Activity.class.getDeclaredField("mActivityInfo");
            field.setAccessible(true);
            ActivityInfo o = (ActivityInfo) field.get(this);
            o.screenOrientation = -1;
            field.setAccessible(false);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


    private void checkToken() {
        //application 初始化设置重写了，如果缓存有从缓存取
        try {
            verifyInfo = HttpRequest.getVerifyInfo();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (null != verifyInfo) {
            String accessToken = verifyInfo.getAccessToken();
            String refreshToken = verifyInfo.getRefreshToken();
            if (!TextUtils.isEmpty(accessToken) && !TextUtils.isEmpty(refreshToken)) {
                updateUserToken(refreshToken);
            } else {
                goToMainActivity(false);
            }
        } else {
            goToMainActivity(false);
        }
    }

    private void updateUserToken(String rfToken) {
        MeDao.getInstance().updateUserToken(rfToken, new BaseCallBack() {
            @Override
            public void success(Object data) {

                RfTokenInfo rfTokenInfo = (RfTokenInfo) data;
                String accessToken = rfTokenInfo.getAccessToken();
                String refreshToken = rfTokenInfo.getRefreshToken();
                String expires = rfTokenInfo.getRefreshToken();
                if (null != verifyInfo) {
                    verifyInfo.setAccessToken(accessToken);
                    verifyInfo.setRefreshToken(refreshToken);
                    verifyInfo.setExpiresIn(expires);
                    HttpRequest.setVerifyInfo(verifyInfo);
                    try {
                        CWSys.setSharedSerializable(BaseConstants.SHARE_KEY_VERITIFY_INFO,
                                verifyInfo);

                        LoginToken loginToken = LoginToken.queryTokenAndUserInfo(getContentResolver());
                        if (null != loginToken) {
                            loginToken.setReftoken(rfTokenInfo.getRefreshToken());
                            loginToken.setToken(rfTokenInfo.getAccessToken());
                            LoginToken.updateProviderToken(getContentResolver(), loginToken);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    Intent inTeIntent = new Intent(LoginToken.ACTION_LOGIN_SUCCESS);
                    inTeIntent.putExtra(LoginToken.IS_BIND_PHONE, LoginUtil.isBindPhone());
                    sendBroadcast(inTeIntent);
                    //上报登录信息
                    FeedbackUtil.getInstance().asyncUploadUserLogin();
                    goToMainActivity(true);
                } else {
                    goToMainActivity(false);
                }


            }

            @Override
            public void failed(int errorCode, Object data) {
                goToMainActivity(false);
            }

            @Override
            public void failed(Object data) {
                goToMainActivity(true);
            }
        });
    }

    private void getIsFirstUse() {
        //判断第一次进入该版本
        packageName = getPackageName();
        try {
            isFirstUse = CWSys.getSharedBoolean("isFirstUse" + packageName, true);
            privacyAgreement = CWSys.getSharedBoolean("privacyAgreement" + packageName + getPackageManager()
                    .getPackageInfo(getPackageName(), 0).versionName, false);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (privacyAgreement) {
            PackageManager packageManager = getPackageManager();
            packageManager.setComponentEnabledSetting(new ComponentName(SplashActivityDef.this, MyGradeWidgetProvider.class),
                    PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                    PackageManager.DONT_KILL_APP);
            packageManager.setComponentEnabledSetting(new ComponentName(SplashActivityDef.this, HomeworkWidgetProvider.class),
                    PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                    PackageManager.DONT_KILL_APP);
        }
    }

    private void goToMainActivity(boolean isLogin) {
        if (isFirstUse) {
            MeJumpManager.jumpFirstAgreementActivity(R.string.go_back, SplashActivityDef.this, getString(R.string.agreement_url), getString(R.string.agreement_private), AgreementActivity.WECOME_ACTION);//跳转隐私协议
//            MeJumpManager.jumpAgreementActivity(R.string.go_back, SplashActivity.this, getString(R.string.agreement_url), getString(R.string.agreement_private), AgreementActivity.WECOME_ACTION);
        } else {
            //跳转main
            if (isLogin && privacyAgreement) {//用户已经登录
                if (LoginUtil.isBindPhone()) {
                    EJumpManager.jumpToMain(0, SplashActivityDef.this);
                } else {
                    MeJumpManager.jumpToBindPhoneActivity(R.string.go_back, SplashActivityDef.this, "", "2");
                }

            } else {//用户未登录
                EJumpManager.jumpToLogin(0, SplashActivityDef.this);
            }
        }
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                SplashActivityDef.this.finish();
            }
        }, 300);

    }
    /*------------------------------------------pad---------------------------------------------------*/

    /**
     * pad环境 专用
     */
    private void queryTokenFromPad() {


        mLoginToken = LoginToken.queryTokenAndUserInfo(getContentResolver());

        if (mLoginToken == null || isReLogin) {
            Log.e(TAG, "数据库中没有数据");
            //跳转launcher  登录
            isReLogin = false;
            LoginToken.goToUnifiedLogin(this);
            return;
        }

        verifyInfo = new BaseRequest.VerifyInfo();
        verifyInfo.setClientId(EConstants.CLIENT_ID);
        verifyInfo.setClientIp(BaseApplication.getInstance().getAPP_IP());
        verifyInfo.setOauthVersion("2.0");
        verifyInfo.setScope("all");
        verifyInfo.setAccessToken(mLoginToken.getToken());
        verifyInfo.setRefreshToken(mLoginToken.getReftoken());
        verifyInfo.setExpiresIn(mLoginToken.getExpresin());
        HttpRequest.setVerifyInfo(verifyInfo);
        updateUserTokenPad(mLoginToken.getReftoken());
    }


    private void updateUserTokenPad(String rfToken) {
        MeDao.getInstance().updateUserToken(rfToken, new BaseCallBack() {
            @Override
            public void success(Object data) {

                RfTokenInfo rfTokenInfo = (RfTokenInfo) data;
                String accessToken = rfTokenInfo.getAccessToken();
                String refreshToken = rfTokenInfo.getRefreshToken();
                String expires = rfTokenInfo.getRefreshToken();

                if (null != verifyInfo) {
                    verifyInfo.setAccessToken(accessToken);
                    verifyInfo.setRefreshToken(refreshToken);
                    verifyInfo.setExpiresIn(expires);
                    HttpRequest.setVerifyInfo(verifyInfo);
                    try {
                        CWSys.setSharedSerializable(BaseConstants.SHARE_KEY_VERITIFY_INFO,
                                verifyInfo);

                        LoginToken loginToken = LoginToken.queryTokenAndUserInfo(getContentResolver());
                        if (null != loginToken) {
                            loginToken.setReftoken(rfTokenInfo.getRefreshToken());
                            loginToken.setToken(rfTokenInfo.getAccessToken());
                            LoginToken.updateProviderToken(getContentResolver(), loginToken);
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    Intent inTeIntent = new Intent(LoginToken.ACTION_LOGIN_SUCCESS);
                    inTeIntent.putExtra(LoginToken.IS_BIND_PHONE, LoginUtil.isBindPhone());
                    sendBroadcast(inTeIntent);
                    //上报登录信息
                    FeedbackUtil.getInstance().asyncUploadUserLogin();
                    goToMainActivityPad(true);

                } else {
                    LoginToken.goToUnifiedLogin(SplashActivityDef.this);
                }


            }

            @Override
            public void failed(int errorCode, Object data) {
                LoginToken.goToUnifiedLogin(SplashActivityDef.this);
            }

            @Override
            public void failed(Object data) {
                goToMainActivityPad(true);
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.e(TAG, "requestCode=" + requestCode + "&resultCode=" + resultCode);
        if (requestCode == LoginToken.REQUEST_CODE_TO_LAUNCHER_LOGIN) {
            Log.d(TAG, "######launcher 登录成功返回#######");
            if (resultCode == RESULT_OK) {
                goToMainActivityPad(true);
            } else {
                finish();
            }
        }
    }

    private void goToMainActivityPad(boolean isLogin) {
        if (isFirstUse) {
            //跳转新手引导
            MeJumpManager.jumpAgreementActivity(R.string.go_back, SplashActivityDef.this, getString(R.string.agreement_url), getString(R.string.agreement_private), AgreementActivity.WECOME_ACTION);
        } else {
            //跳转main
            if (isLogin && privacyAgreement) {
                //用户已经登录
                if (LoginUtil.isBindPhone()) {
                    EJumpManager.jumpToMain(0, SplashActivityDef.this);
                } else {
                    MeJumpManager.jumpToBindPhoneActivity(R.string.go_back, SplashActivityDef.this, "", "2");
                }
            } else {
                //用户未登录
                LoginToken.goToUnifiedLogin(SplashActivityDef.this);
            }
        }
        finish();
    }
}
